package com.ruoyi.statistics.service.impl;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.statistics.mapper.OrderAnalyseMapper;
import com.ruoyi.statistics.service.IOrderAnalyseService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.DateUtils;

/**
 * 订单数据分析Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-18
 */
@Service
public class OrderAnalyseServiceImpl implements IOrderAnalyseService 
{
    @Autowired
    private OrderAnalyseMapper orderAnalyseMapper;

    /**
     * 获取订单核心指标数据
     */
    @Override
    public Map<String, Object> getOrderMetrics(Long orgId, String startDate, String endDate)
    {
        // 设置默认时间范围（覆盖所有数据）
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            startDate = "2025-01-01";
            endDate = "2025-12-31";
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("orgId", orgId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        
        // 获取核心指标统计数据
        Map<String, Object> metrics = orderAnalyseMapper.selectOrderMetrics(params);
        
        // 获取支付状态分布
        List<Map<String, Object>> paymentStatus = orderAnalyseMapper.selectPaymentStatusDistribution(params);
        
        // 获取订单来源分布
        List<Map<String, Object>> orderSource = orderAnalyseMapper.selectOrderSourceDistribution(params);
        
        Map<String, Object> result = new HashMap<>();
        result.put("metrics", metrics);
        result.put("paymentStatus", paymentStatus);
        result.put("orderSource", orderSource);
        
        return result;
    }

    /**
     * 获取订单详情列表
     */
    @Override
    public Map<String, Object> getOrderDetails(Long orgId, String startDate, String endDate, Integer pageNum, Integer pageSize)
    {
        return getOrderDetailsWithParams(orgId, startDate, endDate, pageNum, pageSize, null);
    }
    
    /**
     * 获取订单详情列表（带筛选条件）
     */
    public Map<String, Object> getOrderDetailsWithParams(Long orgId, String startDate, String endDate, Integer pageNum, Integer pageSize, Map<String, Object> filterParams)
    {
        // 设置默认时间范围（覆盖所有数据）
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            startDate = "2025-01-01";
            endDate = "2025-12-31";
        }
        
        System.out.println("查询参数: orgId=" + orgId + ", startDate=" + startDate + ", endDate=" + endDate + ", pageNum=" + pageNum + ", pageSize=" + pageSize);
        System.out.println("筛选条件: " + filterParams);
        
        Map<String, Object> params = new HashMap<>();
        params.put("orgId", orgId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("offset", (pageNum - 1) * pageSize);
        params.put("limit", pageSize);
        
        // 添加筛选条件
        if (filterParams != null) {
            params.putAll(filterParams);
        }
        
        // 移除空值
        params.entrySet().removeIf(entry -> entry.getValue() == null || "".equals(entry.getValue()));
        
        try {
            // 获取订单详情列表
            List<Map<String, Object>> orderList = orderAnalyseMapper.selectOrderDetails(params);
            System.out.println("查询到的订单数据: " + (orderList != null ? orderList.size() : 0) + " 条记录");
            
            // 获取总数
            Integer total = orderAnalyseMapper.selectOrderDetailsCount(params);
            System.out.println("订单总数: " + total);
            
            Map<String, Object> result = new HashMap<>();
            result.put("rows", orderList != null ? orderList : new ArrayList<>());
            result.put("total", total != null ? total : 0);
            
            return result;
        } catch (Exception e) {
            System.err.println("查询订单详情失败: " + e.getMessage());
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>();
            result.put("rows", new ArrayList<>());
            result.put("total", 0);
            return result;
        }
    }

    /**
     * 获取订单转化漏斗数据
     */
    @Override
    public List<Map<String, Object>> getOrderFunnel(Long orgId, String startDate, String endDate)
    {
        // 设置默认时间范围（覆盖所有数据）
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            startDate = "2025-01-01";
            endDate = "2025-12-31";
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("orgId", orgId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        
        // 获取转化漏斗各阶段数据
        Map<String, Object> funnelData = orderAnalyseMapper.selectOrderFunnel(params);
        
        // 构建漏斗数据结构
        List<Map<String, Object>> funnelList = new ArrayList<>();
        
        // 浏览商品
        Map<String, Object> browse = new HashMap<>();
        browse.put("stage", "浏览商品");
        browse.put("value", funnelData.get("browseCount"));
        browse.put("rate", "100%");
        funnelList.add(browse);
        
        // 加入购物车
        Map<String, Object> addCart = new HashMap<>();
        addCart.put("stage", "加入购物车");
        addCart.put("value", funnelData.get("addCartCount"));
        addCart.put("rate", calculateRate(funnelData.get("addCartCount"), funnelData.get("browseCount")));
        funnelList.add(addCart);
        
        // 提交订单
        Map<String, Object> submitOrder = new HashMap<>();
        submitOrder.put("stage", "提交订单");
        submitOrder.put("value", funnelData.get("submitOrderCount"));
        submitOrder.put("rate", calculateRate(funnelData.get("submitOrderCount"), funnelData.get("addCartCount")));
        funnelList.add(submitOrder);
        
        // 支付订单
        Map<String, Object> payOrder = new HashMap<>();
        payOrder.put("stage", "支付订单");
        payOrder.put("value", funnelData.get("payOrderCount"));
        payOrder.put("rate", calculateRate(funnelData.get("payOrderCount"), funnelData.get("submitOrderCount")));
        funnelList.add(payOrder);
        
        // 确认收货
        Map<String, Object> confirmOrder = new HashMap<>();
        confirmOrder.put("stage", "确认收货");
        confirmOrder.put("value", funnelData.get("confirmOrderCount"));
        confirmOrder.put("rate", calculateRate(funnelData.get("confirmOrderCount"), funnelData.get("payOrderCount")));
        funnelList.add(confirmOrder);
        
        return funnelList;
    }

    /**
     * 获取订单趋势数据
     */
    @Override
    public List<Map<String, Object>> getOrderTrend(Long orgId, String startDate, String endDate, String timeType)
    {
        // 设置默认时间范围（最近30天）
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            endDate = DateUtils.getDate();
            startDate = DateUtils.dateTime(DateUtils.addDays(DateUtils.getNowDate(), -30));
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("orgId", orgId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("timeType", timeType);
        
        List<Map<String, Object>> trendData = orderAnalyseMapper.selectOrderTrend(params);
        
        return trendData;
    }

    /**
     * 导出订单分析数据
     */
    @Override
    public void exportOrderData(HttpServletResponse response, Long orgId, String startDate, String endDate) {
        exportOrderDataWithParams(response, orgId, startDate, endDate, null);
    }
    
    /**
     * 导出订单分析数据（带筛选条件）
     */
    public void exportOrderDataWithParams(HttpServletResponse response, Long orgId, String startDate, String endDate, Map<String, Object> filterParams) {
        try {
            // 设置默认时间范围（最近30天）
            if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
                endDate = DateUtils.getDate();
                startDate = DateUtils.dateTime(DateUtils.addDays(DateUtils.getNowDate(), -30));
            }
            
            Map<String, Object> params = new HashMap<>();
            params.put("orgId", orgId);
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            
            // 添加筛选条件
            if (filterParams != null) {
                params.putAll(filterParams);
            }
            
            // 移除空值
            params.entrySet().removeIf(entry -> entry.getValue() == null || "".equals(entry.getValue()));
            
            List<Map<String, Object>> list = orderAnalyseMapper.selectOrderDetailsForExport(params);
            
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = "订单详情数据_" + System.currentTimeMillis() + ".xlsx";
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
            
            // 手动创建Excel文件
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("订单详情数据");
            
            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"订单号", "用户名称", "下单时间", "订单金额", "支付金额", "优惠金额", "支付状态", "商品件数"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }
            
            // 填充数据
            for (int i = 0; i < list.size(); i++) {
                Row row = sheet.createRow(i + 1);
                Map<String, Object> data = list.get(i);
                
                row.createCell(0).setCellValue(String.valueOf(data.get("订单号")));
                row.createCell(1).setCellValue(String.valueOf(data.get("用户名称")));
                row.createCell(2).setCellValue(String.valueOf(data.get("下单时间")));
                row.createCell(3).setCellValue(String.valueOf(data.get("订单金额")));
                row.createCell(4).setCellValue(String.valueOf(data.get("支付金额")));
                row.createCell(5).setCellValue(String.valueOf(data.get("优惠金额")));
                row.createCell(6).setCellValue(String.valueOf(data.get("支付状态")));
                row.createCell(7).setCellValue(String.valueOf(data.get("商品件数")));
            }
            
            // 添加合计行
            if (!list.isEmpty()) {
                Row summaryRow = sheet.createRow(list.size() + 1);
                summaryRow.createCell(0).setCellValue("合计");
                summaryRow.createCell(1).setCellValue("共" + list.size() + "条记录");
                summaryRow.createCell(2).setCellValue("");
                
                // 计算合计金额
                double totalAmount = list.stream().mapToDouble(item -> {
                    Object amt = item.get("订单金额");
                    return amt != null ? Double.parseDouble(amt.toString()) : 0.0;
                }).sum();
                
                double paymentAmount = list.stream().mapToDouble(item -> {
                    Object amt = item.get("支付金额");
                    return amt != null ? Double.parseDouble(amt.toString()) : 0.0;
                }).sum();
                
                double discountAmount = list.stream().mapToDouble(item -> {
                    Object amt = item.get("优惠金额");
                    return amt != null ? Double.parseDouble(amt.toString()) : 0.0;
                }).sum();
                
                int totalQuantity = list.stream().mapToInt(item -> {
                    Object qty = item.get("商品件数");
                    return qty != null ? Integer.parseInt(qty.toString()) : 0;
                }).sum();
                
                summaryRow.createCell(3).setCellValue(String.format("%.2f", totalAmount));
                summaryRow.createCell(4).setCellValue(String.format("%.2f", paymentAmount));
                summaryRow.createCell(5).setCellValue(String.format("%.2f", discountAmount));
                summaryRow.createCell(6).setCellValue("");
                summaryRow.createCell(7).setCellValue(String.valueOf(totalQuantity));
            }
            
            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            // 写入响应流
            workbook.write(response.getOutputStream());
            workbook.close();
            
        } catch (Exception e) {
            throw new RuntimeException("导出订单详情数据失败", e);
        }
    }

    /**
     * 获取订单金额分布数据
     */
    public List<Map<String, Object>> getOrderAmountDistribution(Long orgId, String startDate, String endDate)
    {
        // 设置默认时间范围（覆盖所有数据）
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            startDate = "2025-01-01";
            endDate = "2025-12-31";
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("orgId", orgId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        
        return orderAnalyseMapper.selectOrderAmountDistribution(params);
    }

    /**
     * 计算转化率
     */
    private String calculateRate(Object current, Object previous)
    {
        if (current == null || previous == null) {
            return "0%";
        }
        
        try {
            double currentValue = Double.parseDouble(current.toString());
            double previousValue = Double.parseDouble(previous.toString());
            
            if (previousValue == 0) {
                return "0%";
            }
            
            double rate = (currentValue / previousValue) * 100;
            return String.format("%.1f%%", rate);
        } catch (NumberFormatException e) {
            return "0%";
        }
    }
}